import { Injectable, OnModuleInit } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { connectRedis } from 'st-common-server';
import { EnvNameEnum } from "../env";
import { connect } from "../redis";
import { setRedisKeyPrefix } from "./consts/redis-key.const";

/**
 * Redis 配置服务
 */
@Injectable()
export class RedisService implements OnModuleInit {

  constructor(
    private readonly configService: ConfigService
  ) {
  }

  async onModuleInit() {
    // 从环境变量中获取 Redis Key 前缀
    setRedisKeyPrefix(this.configService.get<string>(EnvNameEnum.REDIS_KEY_PREFIX));
    // 连接 Redis，创建并保存 Redis 连接对象
    await connectRedis({
      host: this.configService.get<string>(EnvNameEnum.REDIS_HOST),
      port: this.configService.get<number>(EnvNameEnum.REDIS_PORT),
      password: this.configService.get<string>(EnvNameEnum.REDIS_PASSWORD),
      isLog: this.configService.get<boolean>(EnvNameEnum.REDIS_IS_LOG)
    });
    await connect({
      host: this.configService.get<string>(EnvNameEnum.REDIS_HOST),
      port: this.configService.get<number>(EnvNameEnum.REDIS_PORT),
      password: this.configService.get<string>(EnvNameEnum.REDIS_PASSWORD),
      isLog: this.configService.get<boolean>(EnvNameEnum.REDIS_IS_LOG)
    });
  }

}
